'''
Created on Oct 6, 2011

@author: hp
'''
import re
import os

from angluin.constant import INSTANCE_FILE, ALPHABET_FILE

def parse_pattern(fname):
    
    fin = open(fname, 'r')
    pos = fname.rfind('/') + 1
    ext = fname[pos:fname.find('.', pos)]
    print ext
    if fname.find('.I.') == -1:
        finst = open(INSTANCE_FILE + ext, 'w')
        falph = open(ALPHABET_FILE + ext, 'w')
    else:
        finst = open(INSTANCE_FILE + 'I.' + ext, 'w')
        falph = open(ALPHABET_FILE + 'I.' + ext, 'w')
    
    alphabet = set()
    try:
        for line in fin.read().split('\n'):
            if len(line) == 0:
                continue
            if line.find(":") != -1 or line.find("=") != -1:
                continue
            finst.write(line + "\n")
            for w in re.split('\s+', line):
                alphabet.add(w)
        
        for w in alphabet:
            falph.write(w + " ")
    finally:
        fin.close()
        finst.close()
        falph.close()

def parse():
    
    for fname in os.listdir("../../data/pat"):
        if fname.find('.pat.') == -1: 
            continue
        parse_pattern("../../data/pat/" + fname)

if __name__ == "__main__":
    #parse_pattern("../../data/pat/arrive.pat.I.2A")
    parse()